import json
import random
import time

import redis
import requests
from flask import make_response, redirect
from flask_restful import reqparse
from tools.my_jwt import jj
from tools.captcha.captcha import captcha
from tools.comm.comm import sendMsg
from tools.myredis import r
from application.models.users.user import SfLogin
from application.models.users.user import *
from db import db

from application.models.users.user import User
from flask import Blueprint,request,jsonify
good_blue = Blueprint("goodblue",__name__)

# 获取训练营里面得所有数据

@good_blue.route('/getxly')
def getxly():
    sql = 'select * from tcourse'
    res = db.find_all(sql)
    return jsonify({'code':200,'msg':'ok','data':res})


# 加入购物车
@good_blue.route('/addgood',methods=["POST"])
def addshop():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()

    if not all({args['userid'],args['id']}):
        return jsonify({'code':400,'msg':'数据不存在'})

    cart = Cart.query.filter(Cart.cid == args['id']).first()
    print(cart)
    if cart:
        sql = "update Cart set count=count+1 where cart.cid=%d"%int(args['id'])
        db.add(sql)
        db.commit()
        return jsonify({'code':200,'msg':'ok'})
    else:
        count = 1
        sql = "insert into cart(userid,cid,count) values('%d','%d','%d')"%(int(args['userid']),int(args['id']),int(count))
        db.add(sql)
        db.commit()
        return jsonify({'code':200,'msg':'加入购物车成功'})


# 展示购物车数据
@good_blue.route('/getcourse',)
def gettcourse():
    uid = request.args.get('userid')
    list = []
    sql = "select * from cart where cart.userid=%d"% int(uid)
    res = db.find_all(sql)
    for i in res:
        sql1 = "select * from tcourse where tcourse.id=%d"%int(i['cid'])
        res1 = db.find_all(sql1)
        for j in res1:
            list.append({
                'id':j['id'],
                'title':j['title'],
                'price':j['price'],
                'count':i['count'],
                'url':j['url'],
                'amount':(j['price'] * i['count'])
            })
    return jsonify({'code':200,'msg':'ok','data':list})


# 购物车数量加
@good_blue.route('/addcount',methods=["POST"])
def Add_count():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()

    if not all({args['id'], args['userid']}):
        return jsonify({'code': 400, 'msg': '数据不存在'})

    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
    res = db.find_all(sql)
    for i in res:
        sql1 = "update Cart set count=count+1 where cart.userid=%d and cart.cid=%d" % (int(i['userid']), int(args['id']))
        db.add(sql1)
        db.commit()
    return jsonify({'code':200,'msg':'ok'})


# 购物车数量减
@good_blue.route('/mincount',methods=["POST"])
def Min_count():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()

    if not all({args['id'], args['userid']}):
        return jsonify({'code': 400, 'msg': '数据不存在'})

    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
    res = db.find_all(sql)
    for i in res:
        sql1 = "update Cart set count=count-1 where cart.userid=%d and cart.cid=%d" % (int(i['userid']), int(args['id']))
        db.add(sql1)
        db.commit()
    return jsonify({'code':200,'msg':'ok'})

# 删除购物车数据
@good_blue.route('/delcount',methods=["POST"])
def Del_count():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()

    if not all({args['id'], args['userid']}):
        return jsonify({'code': 400, 'msg': '数据不存在'})

    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
    res = db.find_all(sql)
    for i in res:
        sql1 = "delete from cart where cart.userid=%d and cart.cid=%d" % (int(i['userid']), int(args['id']))
        db.add(sql1)
        db.commit()
    return jsonify({'code':200,'msg':'ok'})


from tools.comm.comm import get_ali_object
from application.models.users.user import VipRecord
@good_blue.route('/settlement',methods=['POST'])
def settlement():
    # 获取参数
    req = reqparse.RequestParser()
    req.add_argument('userid')
    args = req.parse_args()
    money = 200
    tmoney = money * int(10)
    order_no = str(int(time.time())) + str(args['userid']) + str(random.randint(100, 999))
    # 支付页面 支付
    pay = get_ali_object()
    query_params = pay.direct_pay(
        subject='购物车订单',  # 商品简单描述
        out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=tmoney,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({"code":200,"url":pay_url})



@good_blue.route('/buy',methods=['POST'])
def buy():
    # 获取参数
    data = json.loads(request.data)
    userid = data['userid']
    year = data['year']
    courseid = data['courseid']
    number = data['number']
    price = data['price']
    money = 200
    # 生成订单
    tmoney = money * int(year)
    order_no = str(int(time.time()))+str(userid)+str(random.randint(100,999))
    orders = Orders(order_no=order_no,userid=userid,courseid=courseid,number=number,price=price,money=tmoney,active_money=tmoney,status=1)
    db.session.add(orders)
    db.session.commit()
    pay = get_ali_object()
    query_params = pay.direct_pay(
        subject='test',  # "充值服务",  # 商品简单描述
        out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(1.00),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })

    # __tablename__ = "orders"
    # order_no = db.Column(db.Integer) # 订单号
    # userid = db.Column(db.Integer, db.ForeignKey('user.id')) # 用户id
    # courseid = db.Column(db.Integer) # 课程id
    # number = db.Column(db.Integer) # 数量
    # price = db.Column(db.Float) # 价格
    # tmoney = db.Column(db.Float) # 总价格
    # status = db.Column(db.Integer, default=1) # 状态
    # trans_no = db.Column(db.String(200)) # 流水号